package com.cola.colaboot.config.security;

import com.cola.colaboot.module.system.pojo.SysAccess;
import com.cola.colaboot.module.system.pojo.SysUser;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class RBACService {
    private static final Set<String> passUrls = new HashSet<>();
    static {//放行规则
        passUrls.add("/sysCode/getCodeImg");
    }

    public boolean hasAccess(HttpServletRequest request, Authentication auth) {
        try{
            String url = request.getRequestURI();
            if(passUrls.contains(url)){
                return true;
            }
            SysUser user = (SysUser) auth.getPrincipal();
            if (1 == user.getRoleId()){//本人偷懒写法，请自行在sys_role_access表中配置正确角色权限关系
                return true;
            }
            for (SysAccess access:(List<SysAccess>) user.getAuthorities()) {
                if(url.equals(access.getAccessUrl())){
                    return true;
                }
            }
            return false;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return false;
        }
    }
}
